window.onload = function () {

  /*
   * obj：指定的父容器节点，其下运动对象是img
   * timespan: 动画播放，每一帧的时间间隔
   * deltay：每一帧移动的高度
   * maxHeight：图片的最大高度
   */
  let dsprite = (obj, timespan, deltay, maxHeight) => {
    // 获取 img 的 delta y
    let getCurDeltay = (obj) => {
      let img = obj.querySelector("img");
      let _transform = img.style.transform;
      let reg = _transform.match(/\((.*?)px\)/);
      let deltay = parseInt(reg[1]) || 0;
      return deltay;
    };

    // 设置 img 的 delta y
    let setCurDeltay = (obj, deltay) => {
      let img = obj.querySelector("img");
      let str = `transform: translateY(${deltay}px);`;
      img.style = str;
    };

    let ani_time = null;
    let _maxHeight = maxHeight - deltay;
    let ani_diret = 1; // 1是正向，-1是反向
    obj.addEventListener("mouseenter", (event) => {
      // console.log("enter");
      ani_diret = 1;
      if (!ani_time) {
        // 没有运行时间函数，就开始动画
        // console.log("setup time");
        ani_time = setInterval(() => {
          let _curY = getCurDeltay(obj);
          let newY = _curY - ani_diret * deltay;
          // console.log(`newY=${newY}`);
          if (newY <= -_maxHeight) {
            newY = -_maxHeight;
            setCurDeltay(obj, newY);
          } else if (newY >= 0) {
            newY = 0;
            setCurDeltay(obj, newY);
            if ((ani_diret = -1)) {
              clearInterval(ani_time);
              ani_time = null;
              // console.log("clear time");
            }
          } else {
            setCurDeltay(obj, newY);
          }
        }, timespan);
      }
    });

    obj.addEventListener("mouseleave", (event) => {
      // console.log("leave");
      if (ani_time) ani_diret = -1;
    });
  };

  let spr1 = document.querySelector(".spr");
  dsprite(spr1, 40, 120, 2880);
};
